﻿using System;
using System.Collections.Generic;
using System.Text;

namespace B4ALL.Cache.Singleton
{
    [Serializable()]
    public class CacheSingletonKey
    {

        private const String EMPTY_PARAMETER = "";

        public CacheSingletonKey(String objectTypeSrc)
        {
            objectType = objectTypeSrc;
        }


        private String objectType;
        public String ObjectType
        {
            get { return objectType; }
        }

        private Dictionary<String, Object> parameters = null;
        public Dictionary<String, Object> Parameters
        {
            get {
                if (parameters == null)
                    parameters = new Dictionary<String, Object>();

                return parameters;
            }
        }

        /// <summary>
        /// Returns key in string format, from data storage in cache system
        /// </summary>
        /// <returns>Key, as used in cache system</returns>
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(objectType + ":");
            
            foreach (KeyValuePair<String, Object> keyPair in parameters)
            {
                if (keyPair.Value == null)
                    sb.Append(String.Format("[{0}:{1}]", keyPair.Key, EMPTY_PARAMETER));
                else
                    sb.Append(String.Format("[{0}:{1}]", keyPair.Key, keyPair.Value.ToString().ToLower()));
            }

            return sb.ToString();
        }

        /// <summary>
        /// Returns regex, for find object in cache system with partial parameters
        /// </summary>
        /// <returns>Regular expression for finding existing object in cache system</returns>
        public String ToRegex()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("^" + objectType + ":");

            if (parameters == null)
                return sb.ToString();

            foreach (KeyValuePair<String, Object> keyPair in parameters)
            {
                if (keyPair.Value == null)
                    sb.Append(String.Format(@"\[{0}:{1}\]", keyPair.Key, ".*"));
                else
                    sb.Append(String.Format(@"\[{0}:{1}\]", keyPair.Key, keyPair.Value.ToString().ToLower()));
            }

            return sb.ToString();
        }
    }
}
